package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.*;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class PathRename {

	public static void main(String[] args) throws IOException {
		Path path = Paths.get("E:", "Copy/", "test.txt");
		System.out.println(path + "重命名为: " + rename(path, "E:/Copy/test1.txt") + " 成功");
	}

	private static Path rename(Path path, String name) throws IOException {
		Path target = path.resolveSibling(name);

		if (Files.isDirectory(target)) {
			deleteDirectory(target);
		}

		return Files.move(path, target, StandardCopyOption.REPLACE_EXISTING);
	}

	private static void deleteDirectory(Path directory) throws IOException {
		if (!Files.exists(directory)) {
			return;
		}

		cleanDirectory(directory);
		Files.delete(directory);
	}

	public static void move(Path file, Path outputDir) throws Exception {
		if (Files.isRegularFile(file)) {
			Files.createDirectories(outputDir);
			Files.move(file,
					outputDir.resolve(file.getFileName().toString()),
					StandardCopyOption.REPLACE_EXISTING);
		} else if (Files.isDirectory(file)) {
			Files.createDirectories(outputDir);
			DirectoryStream<Path> files = Files.newDirectoryStream(file);
			for (Path f : files) {
				Path target = outputDir.resolve(f.getFileName().toString());

				if (Files.isDirectory(target)) {
					cleanDirectory(target);
				}

				Files.move(f, target, StandardCopyOption.REPLACE_EXISTING);
			}
			files.close();
			Files.delete(file);
		}
	}

	private static void cleanDirectory(Path directory) throws IOException {
		if (!Files.exists(directory)) {
			String message = directory + " 不存在";
			throw new IllegalArgumentException(message);
		}

		if (!Files.isDirectory(directory)) {
			String message = directory + " 不是文件夹";
			throw new IllegalArgumentException(message);
		}

		DirectoryStream<Path> directoryStream = Files
				.newDirectoryStream(directory);
		IOException exception = null;
		for (Path p : directoryStream) {
			try {
				delete(p);
			} catch (IOException ioe) {
				exception = ioe;
			}
		}
		directoryStream.close();

		if (exception != null) {
			throw exception;
		}
	}

	private static void delete(Path fileOrDirectory) throws IOException {
		if (Files.isDirectory(fileOrDirectory)) {
			deleteDirectory(fileOrDirectory);
		} else {
			Files.deleteIfExists(fileOrDirectory);
		}
	}
}
